package cn.vire.electric.simulation.netty.server;

/**
 */

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelMatchers;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * Handles a server-side channel.
 */
@Slf4j
public class DiscardServerHandler extends SimpleChannelInboundHandler<String> {
    ChannelGroup channelGroup;
    Channel broadcastClient;
    public DiscardServerHandler() {
    }
    public DiscardServerHandler(ChannelGroup channelGroup,Channel broadcastClient) {
        this.channelGroup = channelGroup;
        this.broadcastClient = broadcastClient;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        log.info("收到报文:[{}],[{}]", msg, ctx.channel().toString());
        ctx.writeAndFlush("收到报文:[" + msg + "]");
        String msgs = "链接[" + ctx.channel().remoteAddress().toString() + "]发送了数据[" + msg + "]";
        channelGroup.writeAndFlush(msgs, ChannelMatchers.isNot(ctx.channel()));
        broadcastClient.writeAndFlush(msgs);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("收到连接:[{}]", ctx.channel().toString());
        channelGroup.add(ctx.channel());
        InetSocketAddress socketAddress = ((InetSocketAddress) ctx.channel().remoteAddress());
        ctx.writeAndFlush("连接成功");
        String msgs = "新链接加入了[" + socketAddress.toString() + "]";
        channelGroup.writeAndFlush(msgs);
        broadcastClient.writeAndFlush(msgs);
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress socketAddress = ((InetSocketAddress) ctx.channel().remoteAddress());
        ctx.writeAndFlush("连接断开");
        log.info("连接断开:[{}]", ctx.channel().toString());
        String msgs = "链接断开了[" + socketAddress.toString() + "],当前连接数[" + channelGroup.size() + "]";
        channelGroup.writeAndFlush(msgs);
        broadcastClient.writeAndFlush(msgs);
        super.channelInactive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (4)
        log.error("捕获exceptionCaught", cause);
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                ctx.close();
            } else if (e.state() == IdleState.WRITER_IDLE) {
                ctx.writeAndFlush("你还连吗?不连我关了啊");
            }
        }
    }
}
